# !/usr/bin/env python
# -*- coding: utf-8 -*-

# @File   : xmlparse.py
# @Time   : 2022/5/24 5:35 下午
# @Author : yujianhui
import json
import xml.etree.cElementTree as ET
from frame.vo.expectvo import ExceptVo
from frame.vo.reqvo import ReqVO
from frame.vo.variablevo import VariableVo
from frame.vo.casevo import CaseVo


def xmlparse(xml_path: str) -> list[CaseVo]:
    """
    解析xml为case对象列表
    :param xml_path: xml文件绝对路径
    :return:
    """
    # 解析xml
    tree = ET.parse(xml_path)
    root = tree.getroot()
    # 获取所有case
    cases = root.findall('case')
    case_vos = []
    for case in cases:
        # 获取request
        request = case.find('request')
        request_json = json.loads(request.text)
        req_vo = ReqVO(**request_json)

        # 获取所有expect
        expects_node=case.find('expects')
        expects = expects_node.findall('expect')
        expect_vos = []
        for expect in expects:
            valid_type = expect.get('validType')
            expected = expect.find('expected').text
            expect_vo = ExceptVo(valid_type, expected)
            expect_vos.append(expect_vo)

        # 获取所有variable
        variables_node=case.find('variables')
        variables = variables_node.findall('variable')
        variable_vos = []
        for variable in variables:
            variable_vo = VariableVo(variable.find('key').text, variable.find('value').text)
            variable_vos.append(variable_vo)

        # 组装case对象
        case_vo = CaseVo(case.get('id'), case.get('tag'), case.get('description'), case.get('signType'), req_vo,
                         expect_vos, variable_vos)
        # 保存所有case
        case_vos.append(case_vo)
    return case_vos
